/***************************************************************************//**
 * @file MSc_Matrix.h
 * @author  Marek M. Cel <marekcel@mscsim.org>
 *
 * @section LICENSE
 *
 * Copyright (C) 2013 Marek M. Cel
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/
#ifndef MSC_MATRIX_H
#define MSC_MATRIX_H

////////////////////////////////////////////////////////////////////////////////

#include <sstream>

#include "MSc_Exception.h"
#include "MSc_Vector.h"

////////////////////////////////////////////////////////////////////////////////

/**	Matrix base class template. */
template <int ROWS,int COLS>
class MSc_Matrix
{
public:

    /** Constructor. */
    MSc_Matrix() :
        m_rows ( ROWS ),
        m_cols ( COLS ),
        m_size ( ROWS * COLS )
    {
        double * item = m_items;

        for ( int i = 0; i < m_size; i++ )
        {
            (*item) = 0.0; item++; // m_items[ i ] = 0.0;
        }
    }

    /** Copy constructor. */
    MSc_Matrix( const MSc_Matrix<ROWS,COLS> &mtrx ) :
        m_rows ( ROWS ),
        m_cols ( COLS ),
        m_size ( ROWS * COLS )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] = mtrx.m_items[ i ];
        }
    }

    /** @return "true" if all items are valid */
    virtual bool isValid() const
    {
        return MSc_Utils::isValid( m_items, m_size );
    }

    /** Puts matrix items into given array. */
    virtual void getArray( double items[] ) const
    {
        for ( int i = 0; i < m_size; i++ )
        {
            items[ i ] = m_items[ i ];
        }
    }

    /**
     * This function is bound-checked which may affect performance.
     * Throws MSc_Exception when row or column index is out of range.
     * @return matrix item of given indicies.
     */
    virtual double getItem( int row, int col ) const
    {
        if (    ( ( row < 0 ) || ( row >= m_rows ) )
             || ( ( col < 0 ) || ( col >= m_cols ) ) )
        {
            MSc_Exception e;

            e.setType( MSc_Exception::ArrayIndexOverLimit );
            e.setFile( __FILE__ );
            e.setLine( __LINE__ );
            e.setInfo( "Array index over limit." );

            throw e;
        }

        return m_items[ row * m_cols + col ];
    }

    /** Sets matrix items from given array. */
    virtual void setArray( const double items[] )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] = items[ i ];
        }
    }

    /**
     * This function sets matrix item of given indicies.
     * This function is bound-checked which may affect performance.
     * Throws MSc_Exception when row or column index is out of range.
     */
    virtual void setItem( int row, int col, double value )
    {
        if (    ( ( row < 0 ) || ( row >= m_rows ) )
             || ( ( col < 0 ) || ( col >= m_cols ) ) )
        {
            MSc_Exception e;

            e.setType( MSc_Exception::ArrayIndexOverLimit );
            e.setFile( __FILE__ );
            e.setLine( __LINE__ );
            e.setInfo( "Array index over limit." );

            throw e;
        }

        m_items[ row * m_cols + col ] = value;
    }

    /** This function returns string represtation of the matrix. */
    virtual std::string toString()
    {
        std::stringstream ss;

        for ( int i = 0; i < m_size; i++ )
        {
            if ( i != 0 ) ss << ",";

            ss << m_items[ i ];
        }

        return ss.str();
    }

    /**
     * Items accessor. Please notice that this operator is NOT bound-checked.
     * If you want bound-checked item accessor use getItem(int,int) or
     * setItem(int,int,double) functions.
     */
    inline double operator() ( int row, int col ) const
    {
#       ifdef _DEBUG
        if (    ( ( row < 0 ) || ( row >= m_rows ) )
             || ( ( col < 0 ) || ( col >= m_cols ) ) )
        {
            MSc_Exception e;

            e.setType( MSc_Exception::ArrayIndexOverLimit );
            e.setFile( __FILE__ );
            e.setLine( __LINE__ );
            e.setInfo( "Array index over limit." );

            throw e;
        }
#       endif

        return m_items[ row * m_cols + col ];
    }

    /**
     * Items accessor. Please notice that this operator is NOT bound-checked.
     * If you want bound-checked item accessor use getItem(int,int) or
     * setItem(int,int,double) functions.
     */
    inline double& operator() ( int row, int col )
    {
#       ifdef _DEBUG
        if (    ( ( row < 0 ) || ( row >= m_rows ) )
             || ( ( col < 0 ) || ( col >= m_cols ) ) )
        {
            MSc_Exception e;

            e.setType( MSc_Exception::ArrayIndexOverLimit );
            e.setFile( __FILE__ );
            e.setLine( __LINE__ );
            e.setInfo( "Array index over limit." );

            throw e;
        }
#       endif

        return m_items[ row * m_cols + col ];
    }

    /** Assignment operator. */
    MSc_Matrix<ROWS,COLS>& operator= ( const MSc_Matrix<ROWS,COLS> &mtrx )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] = mtrx.m_items[ i ];
        }

        return (*this);
    }

    /** Addition operator. */
    MSc_Matrix<ROWS,COLS> operator+ ( const MSc_Matrix<ROWS,COLS> &mtrx ) const
    {
        MSc_Matrix<ROWS,COLS> result;
        
        for ( int i = 0; i < m_size; i++ )
        {
            result.m_items[ i ] = m_items[ i ] + mtrx.m_items[ i ];
        }

        return result;
    }

    /** Subtraction operator. */
    MSc_Matrix<ROWS,COLS> operator- ( const MSc_Matrix<ROWS,COLS> &mtrx ) const
    {
        MSc_Matrix<ROWS,COLS> result;
        
        for ( int i = 0; i < m_size; i++ )
        {
            result.m_items[ i ] = m_items[ i ] - mtrx.m_items[ i ];
        }

        return result;
    }

    /** Multiplication operator (by scalar). */
    MSc_Matrix<ROWS,COLS> operator* ( double value ) const
    {
        MSc_Matrix<ROWS,COLS> result;

        for ( int i = 0; i < m_size; i++ )
        {
            result.m_items[ i ] = m_items[ i ] * value;
        }

        return result;
    }

    /** Multiplication operator (by matrix). */
    MSc_Matrix<ROWS,COLS> operator* ( const MSc_Matrix<ROWS,COLS> &mtrx ) const
    {
        MSc_Matrix<ROWS,COLS> result;

        for ( int r = 0; r < m_rows; r++ )
        {
            for ( int c = 0; c < m_cols; c++ )
            {
                result(r,c) = 0.0;

                for ( int i = 0; i < m_cols; i++ )
                {
                    result(r,c) += ( m_items[ r*m_cols + i ] * mtrx(i,c) );
                }
            }
        }

        return result;
    }

    /** Multiplication operator (by vector). */
    MSc_Vector<ROWS> operator* ( const MSc_Vector<COLS> &vect ) const
    {
        MSc_Vector<ROWS> result;

        for ( int r = 0; r < m_rows; r++ )
        {
            result(r) = 0.0;

            for ( int c = 0; c < m_cols; c++ )
            {
                result(r) += ( m_items[ r*m_cols + c ] * vect(c) );
            }
        }

        return result;
    }

    /** Division operator (by scalar). */
    MSc_Matrix<ROWS,COLS> operator/ ( double value ) const
    {
        MSc_Matrix<ROWS,COLS> result;

        for ( int i = 0; i < m_size; i++ )
        {
            result.m_items[ i ] = m_items[ i ] / value;
        }

        return result;
    }

    /** Unary addition operator. */
    MSc_Matrix<ROWS,COLS>& operator+= ( const MSc_Matrix<ROWS,COLS> &mtrx )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] += mtrx.m_items[ i ];
        }

        return (*this);
    }

    /** Unary subtraction operator. */
    MSc_Matrix<ROWS,COLS>& operator-= ( const MSc_Matrix<ROWS,COLS> &mtrx )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] -= mtrx.m_items[ i ];
        }

        return (*this);
    }

    /** Unary multiplication operator (by scalar). */
    MSc_Matrix<ROWS,COLS>& operator*= ( double value )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] *= value;
        }

        return (*this);
    }

    /** Unary division operator (by scalar). */
    MSc_Matrix<ROWS,COLS>& operator/= ( double value )
    {
        for ( int i = 0; i < m_size; i++ )
        {
            m_items[ i ] /= value;
        }

        return (*this);
    }

    /** Equality operator. */
    bool operator== ( const MSc_Matrix<ROWS,COLS> &mtrx ) const
    {
        bool result = true;

        for ( int i = 0; i < m_size; i++ )
        {
            result = result && ( m_items[ i ] == mtrx.m_items[ i ] );
        }

        return result;
    }

    /** Inequality operator. */
    bool operator!= ( const MSc_Matrix<ROWS,COLS> &mtrx ) const
    {
        return !( (*this) == mtrx );
    }

protected:

    double m_items[ ROWS * COLS ];  ///< matrix items

    const int m_rows;   ///< number of rows
    const int m_cols;   ///< number of columns
    const int m_size;   ///< matrix size
};

////////////////////////////////////////////////////////////////////////////////

#endif // MSC_MATRIX_H
